﻿@page "/coder"
@using System.Text
@using System.Text.RegularExpressions
@using Tool.Utils
@inject ISnackbar snackbar
<PageTitle>Coder</PageTitle>
<MudText Typo="Typo.h3" GutterBottom="true">神桥</MudText>
<MudGrid>

	<MudItem xs="9">
		<MudTextField @bind-Value="_sql" Label="sql语句(或者建表语句)" Variant="Variant.Text" Adornment="Adornment.Start"
					  AdornmentIcon="@Icons.Material.Filled.LockPerson" Clearable="true" Lines="12" />
	</MudItem>

	<MudItem xs="3" Class="align-content-center">
		<MudButton Class="align-self-center" FullWidth="true" Disabled="@_processing" OnClick="ConvertToCharpModel" Variant="Variant.Filled" Color="Color.Primary">
			@if (_processing)
			{
				<MudProgressCircular Class="ms-n1" Indeterminate="true" />
				<MudText Class="ms-2">Processing</MudText>
			}
			else
			{
				<MudText>转换成C#实体</MudText>
			}
		</MudButton>
	</MudItem>
	<MudItem xs="12">
		<MudCard>
			<MudCardContent>
				<MudText>查询语句</MudText>
				
					<div>@_selectSql</div>
				
			</MudCardContent>
			
		</MudCard>
	</MudItem>
	<MudItem xs="6">
		<MudCard>
			<MudCardContent>
				<MudText>C#实体</MudText>
				@foreach (var result in _properties)
				{
					<div>@result</div>
				}

			</MudCardContent>
			<MudCardActions>
				<MudButton Variant="Variant.Text" Color="Color.Primary" OnClick="ClearData">清除历史</MudButton>
			</MudCardActions>
		</MudCard>
	</MudItem>
	<MudItem xs="6">
		<MudCard>
			<MudCardContent>
				<MudText>json解析</MudText>
				@foreach (var result in _parseCode)
				{
					<div>@result</div>
				}

			</MudCardContent>
			<MudCardActions>
				<MudButton Variant="Variant.Text" Color="Color.Primary" OnClick="ClearData">清除历史</MudButton>
			</MudCardActions>
		</MudCard>
	</MudItem>
	<MudItem xs="12">
		<MudCard>
			<MudCardContent>
				<MudText>MudTable表格</MudText>
				@foreach (var result in _mudTables)
				{
					@* <MudText Typo="Typo.body2">@result</MudText> *@
					<div>@result</div>
				}
			</MudCardContent>
			<MudCardActions>
				<MudButton Variant="Variant.Text" Color="Color.Primary" OnClick="ClearData">清除历史</MudButton>
			</MudCardActions>
		</MudCard>
	</MudItem>
</MudGrid>
@code {
	private string _sql = string.Empty;
	private string _selectSql = string.Empty;
	private bool _processing = false;
	private List<string> _properties = new List<string>();
	private List<string> _parseCode = new List<string>();
	private List<string> _mudTables = new List<string>();
	private RegexOptions regexOptions = RegexOptions.IgnoreCase | RegexOptions.Multiline;
	private void ConvertToCharpModel()
	{
		_processing = true;
		try
		{
			if (_sql.IsBlank())
			{
				snackbar.Add("SQL语句不能为空", Severity.Warning);
				return;
			}

			var (columns, selectSql) = GetColumns();

			_properties.Clear();
			_mudTables.Clear();
			_parseCode.Clear();
			_selectSql = selectSql;
			_mudTables.Add("<MudTable Items=\"@_items\" @bind-SelectedItems=\"_selectedItems\" Dense=\"true\" Hover=\"true\" Bordered=\"true\" Striped=\"true\" MultiSelection=\"true\" CustomHeader=\"true\" CustomFooter=\"true\">");
			_mudTables.Add("<ToolBarContent>");
			_mudTables.Add("<MudText Typo=\"Typo.h6\">Items</MudText>");
			_mudTables.Add("<MudSpacer />");
			_mudTables.Add("</ToolBarContent>");
			_mudTables.Add("<HeaderContent>");
			_mudTables.Add("<MudTHeadRow Checkable=\"true\">");

			var mudTablesTemp = new List<string>();
			var index = 0;
			foreach (var item in columns)
			{
				if (item == "Id")
				{
					_properties.Add("public long? Id { get; set; }");
					_parseCode.Add($"{item} = item[{index++}].GetString(),");
				}
				else if (item.Contains("Date") || item.Contains("Time"))
				{
					_properties.Add($"public DateTime? {item} {{ get; set; }}");
					_parseCode.Add($"{item} = item[{index++}].GetString(),");
				}

				else if (item.StartsWith("Is"))
				{
					_properties.Add($"public bool? {item} {{ get; set; }}");
					_parseCode.Add($"{item} = item[{index++}].GetInt16(),");
				}
				else
				{
					_properties.Add($"public string? {item} {{ get; set; }}");
					_parseCode.Add($"{item} = item[{index++}].ToString(),");
				}

				_mudTables.Add($"<MudTh>{item}</MudTh>");
				mudTablesTemp.Add($"<MudTd DataLabel=\"{item}\">@context.{item}</MudTd>");
			}
			_mudTables.Add("<MudTh>Action</MudTh>");
			_mudTables.Add($"</MudTHeadRow>");
			_mudTables.Add($"</HeaderContent>");
			_mudTables.Add($"<RowTemplate>");
			mudTablesTemp.Add($"<MudTd DataLabel=\"Action\"><MudButton OnClick=\"() => ShowEvd(context.FilePath)\" Variant=\"Variant.Filled\" Color=\"Color.Info\">查看</MudButton></MudTd>");
			_mudTables.AddRange(mudTablesTemp);
			_mudTables.Add($"</RowTemplate>");
			_mudTables.Add("<FooterContent>");
			_mudTables.Add("<MudTFootRow Checkable=\"true\">");
			_mudTables.Add("<MudTd colspan=\"5\">Selected: @_selectedEvds?.Count</MudTd>");
			_mudTables.Add("</MudTFootRow>");
			_mudTables.Add("</FooterContent>");
			_mudTables.Add("<PagerContent>");
			_mudTables.Add("<MudTablePager />");
			_mudTables.Add("</PagerContent>");
			_mudTables.Add("</MudTable>");
			snackbar.Add("SQL语句已转换为C#模型", Severity.Success);
		}
		catch (Exception ex)
		{
			snackbar.Add($"转换失败: {ex.Message}", Severity.Error);
		}
		finally
		{
			_processing = false;
		}
	}

	private Tuple<List<string>,string> GetColumns()
	{
		var match = Regex.Match(_sql, "create table", regexOptions);

		var tableNameMatch = Regex.Match(_sql, "create table `(.*?)`", regexOptions);
		string tableName = string.Empty;
		List<string> columns = new List<string>();
		List<string> selectColumns = new List<string>();
		if (tableNameMatch.Success)
		{
			tableName = tableNameMatch.Groups[1].Value;
			var matches = Regex.Matches(_sql, "`(.*?)`", regexOptions);
			if (matches.Any())
			{
				foreach (Match item in matches)
				{
					var columnName = item.Groups[1].ToString();
					var columnNamePascalCase = columnName.ToPascalCase();
					if (tableName != columnName && !columns.Contains(columnNamePascalCase))
					{
						columns.Add(columnNamePascalCase);
						selectColumns.Add($"{columnName} as {columnNamePascalCase}");
					}
				}
			}
		}
		else
		{
			columns = _sql.Substring(_sql.IndexOf("SELECT", StringComparison.OrdinalIgnoreCase) + 6, _sql.IndexOf("FROM", StringComparison.OrdinalIgnoreCase) - 6)
					.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
					.Select(c => c.Trim().Split(' ')[0].ToPascalCase())
					.ToList();
		}
		var selectSql = $"select {string.Join(',', selectColumns)} from {tableName}";
		return new(columns, selectSql);
	}

	private void ClearData()
	{
		_properties.Clear();
		_mudTables.Clear();
		_parseCode.Clear();
		snackbar.Add("已清除数据", Severity.Info);
	}
}
